<template>
  <div class="quill-editor">
    <div class="toolbar-extra" v-if="showImageUpload">
      <ImageUpload 
        @success="onImageUploadSuccess"
        @error="onImageUploadError"
      />
    </div>
    <div ref="editorRef" class="editor-container"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import Quill from 'quill'
import 'quill/dist/quill.snow.css'
import ImageUpload from './ImageUpload.vue'

interface Props {
  modelValue?: string
  placeholder?: string
  readonly?: boolean
  height?: string
  showImageUpload?: boolean
}

interface Emits {
  (e: 'update:modelValue', value: string): void
  (e: 'change', value: string): void
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: '',
  placeholder: '请输入内容...',
  readonly: false,
  height: '300px',
  showImageUpload: true
})

const emit = defineEmits<Emits>()

const editorRef = ref<HTMLElement>()
let quill: Quill | null = null

onMounted(() => {
  if (editorRef.value) {
    // 配置工具栏
    const toolbarOptions = [
      [{ 'header': [1, 2, 3, false] }],
      ['bold', 'italic', 'underline', 'strike'],
      [{ 'color': [] }, { 'background': [] }],
      [{ 'list': 'ordered' }, { 'list': 'bullet' }],
      [{ 'align': [] }],
      ['link', 'blockquote', 'code-block'],
      ['clean']
    ]

    // 如果不显示图片上传组件，则在工具栏中添加图片按钮
    if (!props.showImageUpload) {
      toolbarOptions.splice(-1, 0, ['image'])
    }

    quill = new Quill(editorRef.value, {
      theme: 'snow',
      placeholder: props.placeholder,
      readOnly: props.readonly,
      modules: {
        toolbar: toolbarOptions
      }
    })

    // 设置编辑器高度
    if (editorRef.value) {
      const editor = editorRef.value.querySelector('.ql-editor') as HTMLElement
      if (editor) {
        if (props.height === '100%') {
          // 如果是100%高度，让容器自适应
          editor.style.height = '100%'
          editor.style.minHeight = '300px'
          editor.style.maxHeight = 'none'
          editor.style.overflowY = 'auto'
        } else {
          editor.style.height = props.height
          editor.style.minHeight = props.height
        }
      }
    }

    // 设置初始内容
    if (props.modelValue) {
      quill.root.innerHTML = props.modelValue
    }

    // 监听内容变化
    quill.on('text-change', () => {
      const html = quill!.root.innerHTML
      emit('update:modelValue', html)
      emit('change', html)
    })

    // 自定义图片上传处理（如果工具栏有图片按钮）
    if (!props.showImageUpload) {
      const toolbar = quill.getModule('toolbar') as any
      toolbar?.addHandler('image', handleImageUpload)
    }
  }
})

// 监听外部传入的值变化
watch(() => props.modelValue, (newValue) => {
  if (quill && newValue !== quill.root.innerHTML) {
    quill.root.innerHTML = newValue || ''
  }
})

// 监听只读状态变化
watch(() => props.readonly, (newValue) => {
  if (quill) {
    quill.enable(!newValue)
  }
})

// 自定义图片上传处理（工具栏内置）
const handleImageUpload = () => {
  const input = document.createElement('input')
  input.setAttribute('type', 'file')
  input.setAttribute('accept', 'image/*')
  input.click()

  input.onchange = () => {
    const file = input.files?.[0]
    if (file) {
      // 验证文件
      if (!file.type.startsWith('image/')) {
        ElMessage.error('只能上传图片文件')
        return
      }
      
      if (file.size > 5 * 1024 * 1024) {
        ElMessage.error('图片大小不能超过5MB')
        return
      }

      // 转换为Base64（临时方案）
      const reader = new FileReader()
      reader.onload = (e) => {
        const range = quill!.getSelection()
        quill!.insertEmbed(range?.index || 0, 'image', e.target?.result)
      }
      reader.readAsDataURL(file)
    }
  }
}

// 图片上传成功回调
const onImageUploadSuccess = (imageUrl: string) => {
  if (quill) {
    const range = quill.getSelection()
    const index = range?.index || 0
    
    // 插入图片
    quill.insertEmbed(index, 'image', imageUrl)
    
    // 移动光标到图片后面
    quill.setSelection(index + 1)
    
    // 手动触发内容变化事件
    const html = quill.root.innerHTML
    emit('update:modelValue', html)
    emit('change', html)
  }
}

// 图片上传失败回调
const onImageUploadError = (error: string) => {
  ElMessage.error(error)
}

// 获取纯文本内容
const getTextContent = () => {
  return quill?.getText() || ''
}

// 获取内容长度
const getLength = () => {
  return quill?.getLength() || 0
}

// 插入文本
const insertText = (index: number, text: string) => {
  quill?.insertText(index, text)
}

// 格式化文本
const formatText = (index: number, length: number, format: string, value: any) => {
  quill?.formatText(index, length, format, value)
}

// 获取选择范围
const getSelection = () => {
  return quill?.getSelection()
}

// 设置选择范围
const setSelection = (index: number, length = 0) => {
  quill?.setSelection(index, length)
}

// 暴露给父组件的方法
defineExpose({
  getContent: () => quill?.root.innerHTML || '',
  setContent: (content: string) => {
    if (quill) {
      quill.root.innerHTML = content
    }
  },
  getTextContent,
  getLength,
  insertText,
  formatText,
  getSelection,
  setSelection,
  focus: () => quill?.focus(),
  blur: () => quill?.blur(),
  enable: (enabled: boolean) => quill?.enable(enabled)
})
</script>

<style scoped>
.quill-editor {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.toolbar-extra {
  padding: 8px 12px;
  background: #fafafa;
  border: 1px solid #ccc;
  border-bottom: none;
  border-radius: 4px 4px 0 0;
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
}

.editor-container {
  background: white;
  border-radius: 4px;
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.editor-container:has(+ .toolbar-extra) {
  border-radius: 0 0 4px 4px;
}

:deep(.ql-toolbar) {
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
  border-bottom: none;
  border-radius: 4px 4px 0 0;
  flex-shrink: 0;
}

.toolbar-extra + .editor-container :deep(.ql-toolbar) {
  border-top: none;
  border-radius: 0;
}

:deep(.ql-container) {
  border-bottom: 1px solid #ccc;
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
  border-top: none;
  border-radius: 0 0 4px 4px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

:deep(.ql-editor) {
  font-size: 14px;
  line-height: 1.6;
  color: var(--el-text-color-primary);
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  height: 100%;
  box-sizing: border-box;
}

:deep(.ql-editor.ql-blank::before) {
  font-style: normal;
  color: var(--el-text-color-placeholder);
}

:deep(.ql-editor img) {
  max-width: 100%;
  height: auto;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin: 8px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .toolbar-extra {
    padding: 6px 8px;
    flex-wrap: wrap;
  }
  
  :deep(.ql-toolbar) {
    padding: 6px;
  }
  
  :deep(.ql-editor) {
    font-size: 13px;
    padding: 12px;
  }
}
</style>